<template>
  <button
    v-if="!isFollow"
    class="primary-btn"
    :class="{ 'primary-gradient': styleGradient }"
    @click.stop="toggleFollow"
  >
    <Icon size="16" name="follow" v-if="!styleGradient"></Icon>
    {{ $t('common.follow') }}
  </button>
  <button v-else class="cancel-light-btn" @click.stop="toggleFollow">{{ $t('common.following') }}</button>
</template>

<script setup>
import { ref } from 'vue'
import { useAccountStore } from '@/store/account'
import { notifyFollow } from '@/utils/state-broadcast'
import { FOLLOW_UPDATE } from '@/constant'
import { trackEvent } from '@/gtm'
import API from '@/http'

const props = defineProps({
  userId: { type: Number },
  isFollow: { type: Boolean },
  styleGradient: { type: Boolean, default: false },
})

const sending = ref(false)

const { afterLoginAction } = useAccountStore()
const toggleFollow = afterLoginAction($toggleFollow)
function $toggleFollow() {
  if (sending.value) return

  sending.value = true
  const data = {
    type: props.isFollow ? FOLLOW_UPDATE.UNFOLLOW : FOLLOW_UPDATE.FOLLOW,
    aff_follow: props.userId,
  }

  API.Follow.update({
    data,
  })
    .then(() => {
      notifyFollow(props.userId, !props.isFollow)
    })
    .catch((e) => console.warn('Toggle feed like fail: ', e))
    .finally(() => (sending.value = false))

  if (!props.isFollow) {
    trackEvent({ key: 15, meta: { aff: props.userId } })
  }
}
</script>
